using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using Aga.Psad.Backend.Repositories;
using Aga.Psad.Backend.Entities;
using AutoMapper;
using Aga.Psad.Mvc.Models.Clientes;
using Aga.Psad.Mvc.Helpers;

namespace Aga.Psad.Mvc.Controllers
{
    [Authorize(Roles = "Administrador")]
    public class ClientesController : ControllerBase
    {
        public ClientesController()
        {
            InitializeMappers();

            ViewData["Menu"] = "cli";
        }

        private void InitializeMappers()
        {
            Mapper.CreateMap<Cliente, ClienteViewModel>();
            Mapper.CreateMap<ClienteViewModel, Cliente>();
            Mapper.CreateMap<ClienteDeCliente, ClienteDeClienteViewModel>();
            Mapper.CreateMap<ClienteDeClienteViewModel, ClienteDeCliente>();
        }
        //
        // GET: /Clientes/

        public ActionResult Index()
        {
            try 
            {
                ClienteRepository repository = new ClienteRepository();

                var entities = repository.GetAll();
                List<ClienteViewModel> model = Mapper.Map<List<Cliente>, List<ClienteViewModel>>(entities);
                
                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // GET: /Clientes/Details/5

        public ActionResult Details(int id)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();
                Cliente entity = repository.GetById(id);

                ClienteViewModel model = Mapper.Map<Cliente, ClienteViewModel>(entity);

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // GET: /Clientes/Create

        public ActionResult Create()
        {
            try
            {
                ClienteViewModel model = new ClienteViewModel();

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        } 

        // POST: /Clientes/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();

                ClienteViewModel model = new ClienteViewModel();

                UpdateModel(model);

                if (!model.IsValid)
                {
                    foreach (var issue in model.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }

                    return View(model);
                }

                model.Cuit = model.Cuit.Replace("-", string.Empty);

                Cliente entity = Mapper.Map<ClienteViewModel, Cliente>(model);

                repository.Save(entity);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // GET: /Clientes/Edit/5
 
        public ActionResult Edit(int id)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();
                Cliente entity = repository.GetById(id);

                ClienteViewModel model = Mapper.Map<Cliente, ClienteViewModel>(entity);

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // POST: /Clientes/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();

                Cliente entity = repository.GetById(id);
                ClienteViewModel model = Mapper.Map<Cliente, ClienteViewModel>(entity);

                UpdateModel(model);

                if (!model.IsValid)
                {
                    foreach (var issue in model.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }

                    return View(model);
                }

                model.Cuit = model.Cuit.Replace("-", string.Empty);

                entity = Mapper.Map<ClienteViewModel, Cliente>(model, entity);

                repository.Save(entity);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        public ActionResult Remove(int id)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();
                Cliente entity = repository.GetById(id);

                ClienteViewModel model = Mapper.Map<Cliente, ClienteViewModel>(entity);

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Remove(FormCollection collection)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();

                ClienteViewModel model = new ClienteViewModel();

                UpdateModel(model);

                Cliente entity = repository.GetById(model.Id);

                repository.Delete(entity);

                return RedirectToAction("Index");
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        // Clientes de Clientes

        public ActionResult CreateCliente(int id)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();
                Cliente entity = repository.GetById(id);

                ClienteViewModel cliente = Mapper.Map<Cliente, ClienteViewModel>(entity);
                ClienteDeClienteViewModel model = new ClienteDeClienteViewModel { Cliente = cliente };

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult CreateCliente(FormCollection collection)
        {
            try
            {
                ClienteRepository repository = new ClienteRepository();

                ClienteDeClienteViewModel model = new ClienteDeClienteViewModel();

                UpdateModel(model);

                if (!model.IsValid)
                {
                    foreach (var issue in model.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }

                    return View(model);
                }

                model.Cuit.Replace("-", string.Empty);

                Cliente entity = repository.GetById(model.Cliente.Id);
                ClienteDeCliente child = Mapper.Map<ClienteDeClienteViewModel, ClienteDeCliente>(model);

                entity.Clientes.Add(child);

                repository.Save(entity);

                return RedirectToAction("Details", new { id = model.Cliente.Id });
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        public ActionResult RemoveCliente(int id)
        {
            try
            {
                ClienteDeClienteRepository repository = new ClienteDeClienteRepository();
                ClienteDeCliente entity = repository.GetById(id);

                ClienteDeClienteViewModel model = Mapper.Map<ClienteDeCliente, ClienteDeClienteViewModel>(entity);

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult RemoveCliente(FormCollection collection)
        {
            try
            {
                ClienteDeClienteRepository repository = new ClienteDeClienteRepository();

                ClienteDeClienteViewModel model = new ClienteDeClienteViewModel();

                UpdateModel(model);

                ClienteDeCliente entity = repository.GetById(model.Id);

                repository.Delete(entity);

                return RedirectToAction("Details", new { id = model.Cliente.Id });
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // GET: /Clientes/Edit/5

        public ActionResult EditCliente(int id)
        {
            try
            {
                ClienteDeClienteRepository repository = new ClienteDeClienteRepository();

                ClienteDeCliente entity = repository.GetById(id);
                ClienteDeClienteViewModel model = Mapper.Map<ClienteDeCliente, ClienteDeClienteViewModel>(entity);

                return View(model);
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }

        //
        // POST: /Clientes/Edit/5

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditCliente(int id, FormCollection collection)
        {
            try
            {
                ClienteDeClienteRepository repository = new ClienteDeClienteRepository();

                ClienteDeCliente entity = repository.GetById(id);
                ClienteDeClienteViewModel model = Mapper.Map<ClienteDeCliente, ClienteDeClienteViewModel>(entity);

                UpdateModel(model);

                if (!model.IsValid)
                {
                    foreach (var issue in model.GetRuleViolations())
                    {
                        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                    }

                    return View(model);
                }

                model.Cuit.Replace("-", string.Empty);

                //Update fields
                entity.Cuit = model.Cuit;
                entity.RazonSocial = model.RazonSocial;
                entity.Usuario = model.Usuario;

                repository.Save(entity);

                return RedirectToAction("Details", new { id = model.Cliente.Id });
            }
            catch (Exception ex)
            {
                return ShowError(ex);
            }
        }


    }
}
